//应收结算/应收对账

interface IReconciliationViewModel extends ng.IScope{
    /**
     * 结算单据状态下拉
     */
    receiptBillStatusDropDown:ValueListItemResponse[];

    /**
     * 回单附件
     */
    attachmentList:any;
    /**
     * 货物数量单位下拉
     */
    goodsNumUnitDropDown:ValueListItemResponse[];
    /**
     * 应收单价单位
     */
    receivablePriceUnitDropDown:ValueListItemResponse[];
    /**
     * 结算单位下拉
     */
    selectList:SettleListItemResponse[];
    /**
     * 承运单数据
     */
    carrierOData:invoiceManagement;
    /**
     * 订单数据
     */
    orderData:invoiceManagementOrder;
    /**
     * 子单数据
     */
    childerData:invoiceManagementOrderChild;
    /**
     * 发货地省
     */
    shipProvinceCode:string;
    /**
     * 发货地市
     */
    shipCity:string;
    /**
     * 发货地区
     */
    shipArea:string;
    /**
     * 发货地详细地址
     */
    shipdetail:string;
    /**
     * 送货地省
     */
    deliverProvince:string;
    /**
     * 送货地市
     */
    deliverCity:string;
    /**
     * 送货地区
     */
    deliverArea:string;
    /**
     * 送货地详细地址
     */
    deliverdetail:string;
    /**
     * 中转地
     */
    viaAddressList:Array<string>;
    /**
     * 发货时间
     */
    shipTime:string;
    /**
     * 到货时间
     */
    arriveTime:string;
    /**
     * 里程数
     */
    mileage:number;
    /**
     * 货物数量
     */
    goodsNum:number;
    /**
     * 货物数量单位
     */
    goodsNumUnit:string;
    /**
     * 应收列表
     */
    receivableList:Array<FinanceReceivableListItemResponse>;
    /**
     * 应收数据
     */
    receivableData:FinanceReceivableListItemResponse;
    /**
     * 应收单价
     */
    receivablePrice:number;
    /**
     * 应收单位
     */
    receivablePriceUnit:string;
    /**
     * 应收总价
     */
    receivableTotal:number;
    /**
     * 应收说明
     */
    receivableRemarks:string;
    /**
     * 结算单位编号
     */
    settleId:string;
    /**
     * 标题
     */
    title:string;
    /**
     * 是否启用
     */
    priceDis:boolean;
    /**
     * 合同号是否隐藏
     */
    contractNumberDis:boolean;
    /**
     * 审核通过按钮显示隐藏
     */
    auditedBtnHide:boolean;
    /**
     * 退回办理按钮显示隐藏
     */
    returnManageBtnHide:boolean;
    /**
     * 审核通过
     */
    audited:() => void;
    /**
     * 保存
     */
    save:() => void;
    /**
     * 退回办理
     */
    returnManage:() => void;
    /**
     * 取消
     */
    back:() => void;  
    /**
     * 结算单位自动补全
     */
    onSettleAutoComplate:(value:string) => any;
    /**
     * 结算单位选中事件
     */
    onsettleSelected: (select: angucomplete<SettleListItemResponse>) => void;
    reckoner:string;

     /**
     * 点击图片时候触发，用以旋转放大图片
     */
    handleImgClick:(item:any)=>void;
    /**
     * 用以旋转放大的图片的路径
     */
    selectedImgSrc:string;
}

class ReceivableReconciliationController {
    /**
     * 承运单id
     */
    carrierOrderId:string;
    /**
     * 订单id
     */
    orderId:string;
    /**
     * 子单id
     */
    orderChildId:string;
    id:string;
    /**
     * 结算方式
     */
    settleStatus:string;
    /**
     * 应收单价
     */
    price:string;
    /**
     * 应收单价单位
     */
    unit:string;
    /**
     * 应收总价
     */
    totalPrice:string;
    /**
     * 应收编号
     */
    receivableCode:string;
    name:string;;

    //附件
    uploaderList: Array<attachmentList>;
    baseImageUrl: string;

    constructor(private $scope:IReconciliationViewModel,private routeService:routeService,private feeService:IFeeService,private orderService:IorderService,private receivableService:IReceivableService,private valueService:IValueService,
    private settleService:ISettleService,private $location: ng.ILocationService,private $http: ng.IHttpService,private $ngBootbox: BootboxService,
    private $state: angular.ui.IStateService,private commonService:ICommonService,private ossUploaderService:ossUploaderService){
        this.init();
        this.baseImageUrl = this.routeService.getBaseUrl() + "attachment/";
        this.uploaderList = [];
        
    }

    init():void{

        this.carrierOrderId = this.$location.search().carrierOrderId;
        this.orderId = this.$location.search().orderId;
        this.orderChildId = this.$location.search().orderChildId;
        this.id = this.$location.search().Id;
        this.settleStatus = this.$location.search().settleStatus;
        this.totalPrice = this.$location.search().totalPrice;
        this.price = this.$location.search().price;
        this.unit = this.$location.search().unit;   
        this.receivableCode = this.$location.search().receivableCode;;
        this.name = this.$location.search().name;

        this.$scope.title = "应收对账";
        this.$scope.priceDis = true;
        this.$scope.auditedBtnHide = false;
        this.$scope.returnManageBtnHide = false;

        this.$scope.receivableTotal = Number(this.totalPrice);
        this.$scope.receivablePrice = Number(this.price);
        this.$scope.receivablePriceUnit = this.unit;

        if (this.name == "BillManage") {
            this.$scope.title = '账单管理';
            this.$scope.back=()=>{
                window.history.back();
            };
        } else if (this.name == "receivableManage") {
            this.$scope.contractNumberDis = true;
            this.$scope.title = '应收管理';
            this.$scope.back = () => {
                this.$state.go("app.receivable.receivableManagentList",{ name:'receivableManagent'});
            };
        } else if (this.name == "Edit") {
            if(this.settleStatus == "办理"){
                this.$scope.priceDis = false;
                this.$scope.auditedBtnHide = true;
                this.$scope.returnManageBtnHide = true;
               
            }
            else{
                this.$scope.priceDis = true;
            }
            this.$scope.contractNumberDis = true;
            this.$scope.audited = this.audited;
            this.$scope.save = this.save;
            this.$scope.returnManage = this.returnManage;
            this.$scope.back = () => {
                this.$state.go("app.receivable.receivableClose",{name:"Edit"});
            };
        }
        this.loadData();       
        this.loadDropDown();
        this.$scope.onsettleSelected = this.onsettleSelected;
        this.$scope.onSettleAutoComplate = this.onSettleAutoComplate;

        this.$scope.handleImgClick=(item)=>{this.$scope.selectedImgSrc=item.imgSrc;}
    }

    loadData():void{
        /**
         * 获取订单详情
         */
        this.orderService.invoiceManagementDetail(this.carrierOrderId).then((res) => {
            this.$scope.carrierOData = res.data;
            let childerDataAttachment:invoiceManagementOrderChild[] = [];
            res.data.orderList.forEach((items,index) => {
                if(items.id == this.orderId){
                    this.$scope.orderData = items;
                    //默认结算单据状态 是无结算单据
                    if(this.$scope.orderData.settlementStatusEnum == null || this.$scope.orderData.settlementStatusEnum === "" || this.$scope.orderData.settlementStatusEnum == "0"){
                        this.$scope.orderData.settlementStatusEnum = "1";
                    }

                    items.childList.forEach((item,index) => {
                        if(item.id == this.orderChildId){
                            this.$scope.childerData = item;
                        }
                        childerDataAttachment.push(item);
                    });
                }
            });

            // if(this.$scope.orderData.settlementStatusEnum == "0" || this.$scope.orderData.settlementStatusEnum==null){
            //     this.$scope.orderData.settlementStatusEnum = "1";
            // }
            
            /**
             * 获取回单附件
             */
            this.$scope.attachmentList = [];
            const OssFile = this.ossUploaderService.getOssFile();
            childerDataAttachment.forEach((item,index) => {

                if(item.receiptAttachments.length > 0){

                    let tempAttach = {
                        title:'回单'+(index+1),
                        uploader:null,
                        uploaderName:'receipt'+(index+1)+'Uploader'
                    }
                    
                    tempAttach.uploader = new OssFile(this.$scope,tempAttach.uploader,{uploaderList:[],multiple:true})

             
                    item.receiptAttachments.forEach((itemC,indexC)=>{
                        this.uploaderList.push(itemC);
                        
                        tempAttach.uploader.addByAttach(itemC)
                    });
                    this.$scope.attachmentList.push(tempAttach);
                   
                }
            });
            /**
             * 结算单位下拉
             */
            // this.settleService.getList(this.$scope.orderData.clientId, "", "", true, 0, 1).then((res) => {
            //     this.$scope.selectList = res.data.data
            // });
            if(this.orderChildId != "" && this.orderChildId != undefined){
                this.$scope.shipProvinceCode = this.$scope.childerData.shipProvinceStr;
                this.$scope.shipCity = this.$scope.childerData.shipCityStr;
                this.$scope.shipArea = this.$scope.childerData.shipAreaStr;
                this.$scope.shipdetail = this.$scope.childerData.shipAddress;
                this.$scope.viaAddressList = this.$scope.childerData.viaAddressList;
                this.$scope.deliverProvince = this.$scope.childerData.deliverProvinceStr;
                this.$scope.deliverCity = this.$scope.childerData.deliverCityStr;
                this.$scope.deliverArea = this.$scope.childerData.deliverAreaStr;
                this.$scope.deliverdetail = this.$scope.childerData.deliverAddress;
                this.$scope.shipTime = this.$scope.childerData.shipTime;
                this.$scope.arriveTime = this.$scope.childerData.arriveTime;
                this.$scope.mileage = this.$scope.childerData.mileage;

   
            }
            else{
                this.$scope.shipProvinceCode = this.$scope.orderData.originProvinceStr;
                this.$scope.shipCity =this.$scope.orderData.originCityStr;
                this.$scope.shipArea = this.$scope.orderData.originCountyStr;
                this.$scope.shipdetail = this.$scope.orderData.originDetails;
                this.$scope.viaAddressList = this.$scope.orderData.viaAddressList;
                this.$scope.deliverProvince = this.$scope.orderData.destinationProvinceStr;
                this.$scope.deliverCity = this.$scope.orderData.destinationCityStr;
                this.$scope.deliverArea = this.$scope.orderData.destinationCountyStr;
                this.$scope.deliverdetail = this.$scope.orderData.destinationDetails;
                this.$scope.shipTime = this.$scope.orderData.deliveryTime;
                this.$scope.arriveTime = this.$scope.orderData.arrivalTime;
                this.$scope.mileage = this.$scope.orderData.mileage;
            }
        });
        /**
         * 应收信息
         */
        this.receivableService.receivablelist("",null,"","","","","","","","","","","","","",null,this.receivableCode,"",false,"","","","", "","",0,1).then((res) =>{
            let data = res.data.data[0];
            if (this.name == "BillManage" || this.name == "receivableManage") {
                this.$scope.receivablePrice = Number(data.receivablePriceStr);
                this.$scope.receivablePriceUnit = data.receivablePriceUnit;
                this.$scope.receivableTotal = data.receivableTotalPrice;
            }
            this.$scope.receivablePrice = Number(data.receivablePriceStr);
            this.$scope.receivableList = res.data.data;
            this.$scope.receivableData = res.data.data[0];
            this.$scope.settleId = res.data.data[0].settleId;
            this.$scope.reckoner = res.data.data[0].settle;
            $("#reckoner_value").val(res.data.data[0].settle);
            this.$scope.receivableRemarks = data.receivableSummary;
            this.$scope.goodsNum = Number(data.quantityOfGoodsStr);
            this.$scope.goodsNumUnit = data.quantityOfGoodsUnitStr;
        });
    }
  


    /**
     * 枚举下拉(应收对账)
     */
    loadDropDown():void{
        this.$scope.goodsNumUnitDropDown = this.valueService.getGoodQuantityUnitList().data;
        this.$scope.receivablePriceUnitDropDown = this.valueService.getPriceUnitList().data;
        //12.1新增  结算单据状态
        this.$scope.receiptBillStatusDropDown = this.valueService.getReceiptBillStatusDropDown().data;
    }

    /**
     * 审核通过
     */
    audited = () => {
        var settle = $("#reckoner_value").val();
        if (this.$scope.receivablePrice > 0 && (this.$scope.receivablePriceUnit < "1" || this.$scope.receivablePriceUnit == undefined || this.$scope.receivablePriceUnit == null || this.$scope.receivablePriceUnit == "")|| settle =="") {
            this.$ngBootbox.alert("请填写应收单价单位");
            $("#reconform").valid();
            return;
        }
        
        if(this.$scope.title === "应收对账" && (!this.$scope.receivableTotal.toString().trim()||this.$scope.receivableTotal.toString().trim()=="NaN")){
            this.$ngBootbox.alert("请填写应收总价");
            return;
        }
        this.receivableService.edit(this.id, this.$scope.receivablePrice, this.$scope.receivablePriceUnit, this.$scope.receivableTotal, this.$scope.goodsNum, this.$scope.goodsNumUnit, this.$scope.receivableRemarks,this.$scope.settleId, $("#reckoner_value").val()).then(() => {
            this.receivableService.audited(this.id).then((res) => {
                this.$state.go("app.receivable.receivableClose",{name:'receivableCloseList'});
            });
        });
    }
    /**
     * 保存
     */
    save = () => {
        if(!$("#reconform").valid()){return};
        if (this.$scope.receivablePrice > 0 && (this.$scope.receivablePriceUnit < "1" || this.$scope.receivablePriceUnit == undefined || this.$scope.receivablePriceUnit == null || this.$scope.receivablePriceUnit == "")) {
            this.$ngBootbox.alert("请填写应收单价单位");
            $("#reconform").valid();
            return;
        }
        this.receivableService.edit(this.id, this.$scope.receivablePrice, this.$scope.receivablePriceUnit, this.$scope.receivableTotal, this.$scope.goodsNum, this.$scope.goodsNumUnit, this.$scope.receivableRemarks,this.$scope.settleId, $("#reckoner_value").val()).then(() => {
            this.$state.go("app.receivable.receivableClose",{name:'receivableCloseList'});
        });
    }
    /**
     * 退回办理
     */
    returnManage = () =>{
        this.receivableService.returnReceivable(this.id).then((res) => {
            this.$state.go("app.receivable.receivableClose",{name:'receivableCloseList'});
        });
    }
 
 

    
    /**
     * 结算单位选中事件
     */
    onsettleSelected=(selected:angucomplete<SettleListItemResponse>)=>{
        if(selected){
            this.$scope.settleId = selected.description.id;
            $("#reckoner_value").val(selected.description.name)

        }else{
            this.$scope.settleId = "";
        }
    }

    /**
     * 结算单位
     */
    onSettleAutoComplate = (value: string) => {
        if (!this.$scope.orderData.clientId) { return; };
        return this.settleService.getList(this.$scope.orderData.clientId, value, "", true, 0, 5).then(result => {
            return result.data.data;
        });
    }
}

angular.module("tms").controller("receivableReconciliationController", ["$scope","routeService","feeService","orderService","receivableService",
    "valueService","settleService","$location","$http","$ngBootbox","$state","commonService","ossUploaderService", ReceivableReconciliationController]);